import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface LogBasketItem {
  id: string
  timestamp: string
  level: string
  source?: string
  message: string
  filePath: string
  lineNumber?: number
  rawContent: string
  logType: 'operation' | 'framework' | 'debug' | 'component'
  component?: string
  userInfo?: string  // 添加用户信息字段
  workspaceId: string
  addedAt: Date
  logIndex?: number  // 日志序号，用于去重
}

export const useLogBasketStore = defineStore('logBasket', () => {
  // 日志篮中的日志项
  const logItems = ref<LogBasketItem[]>([])
  
  // 从localStorage恢复数据
  function initializeFromStorage() {
    try {
      const storedData = localStorage.getItem('logBasketStore')
      if (storedData) {
        const parsedData = JSON.parse(storedData)
        logItems.value = parsedData.map((item: any) => ({
          ...item,
          addedAt: new Date(item.addedAt)
        }))
        console.log('从localStorage恢复了日志篮数据，项目数量:', logItems.value.length)
      }
    } catch (error) {
      console.error('从localStorage恢复日志篮数据失败:', error)
    }
  }
  
  // 保存到localStorage
  function saveToStorage() {
    try {
      localStorage.setItem('logBasketStore', JSON.stringify(logItems.value))
      console.log('日志篮数据已保存到localStorage')
    } catch (error) {
      console.error('保存日志篮数据到localStorage失败:', error)
    }
  }
  
  // 计算日志内容的hash值
  function calculateLogHash(item: Omit<LogBasketItem, 'id' | 'addedAt'>): string {
    // 组合日志类型、关键内容和时间信息
    const contentToHash = `${item.logType}|${item.message?.trim() || ''}|${item.source?.trim() || ''}|${item.level?.trim() || ''}|${item.component?.trim() || ''}|${item.userInfo?.trim() || ''}|${item.timestamp?.trim() || ''}`
    
    // 简单的hash算法：将字符串转换为数字hash
    let hash = 0
    if (contentToHash.length === 0) return hash.toString()
    
    for (let i = 0; i < contentToHash.length; i++) {
      const char = contentToHash.charCodeAt(i)
      hash = ((hash << 5) - hash) + char
      hash = hash & hash // 转换为32位整数
    }
    
    return hash.toString()
  }
  
  // 检查日志是否重复
  function isLogDuplicate(item: Omit<LogBasketItem, 'id' | 'addedAt'>): boolean {
    const newItemHash = calculateLogHash(item)
    
    return logItems.value.some(existingItem => {
      const existingItemHash = calculateLogHash(existingItem)
      return newItemHash === existingItemHash
    })
  }

  // 添加日志项到日志篮
  function addLogItem(item: Omit<LogBasketItem, 'id' | 'addedAt'>) {
    // 检查是否重复
    if (isLogDuplicate(item)) {
      console.log('日志项已存在，跳过添加:', item)
      return null
    }
    
    const newItem: LogBasketItem = {
      ...item,
      id: generateId(),
      addedAt: new Date()
    }
    
    logItems.value.push(newItem)
    saveToStorage()
    console.log('日志项已添加到日志篮:', newItem)
    
    return newItem
  }
  
  // 从日志篮移除日志项
  function removeLogItem(id: string) {
    const index = logItems.value.findIndex(item => item.id === id)
    if (index > -1) {
      const removedItem = logItems.value.splice(index, 1)[0]
      saveToStorage()
      console.log('日志项已从日志篮移除:', removedItem)
      return removedItem
    }
    return null
  }
  
  // 清理重复的日志项
  function cleanDuplicateLogs() {
    const uniqueLogs: LogBasketItem[] = []
    const seen = new Set<string>()
    
    logItems.value.forEach(item => {
      // 使用hash值作为唯一标识符
      const itemHash = calculateLogHash(item)
      
      if (!seen.has(itemHash)) {
        seen.add(itemHash)
        uniqueLogs.push(item)
      } else {
        console.log('发现重复日志，已跳过:', item)
      }
    })
    
    const removedCount = logItems.value.length - uniqueLogs.length
    if (removedCount > 0) {
      logItems.value = uniqueLogs
      saveToStorage()
      console.log(`清理完成，移除了 ${removedCount} 条重复日志`)
    } else {
      console.log('没有发现重复日志')
    }
    
    return removedCount
  }

  // 清空日志篮
  function clearLogBasket() {
    logItems.value = []
    saveToStorage()
    console.log('日志篮已清空')
  }
  
  // 获取指定工作区的日志项
  function getLogItemsByWorkspace(workspaceId: string): LogBasketItem[] {
    return logItems.value.filter(item => item.workspaceId === workspaceId)
  }
  
  // 获取所有日志项
  function getAllLogItems(): LogBasketItem[] {
    return logItems.value
  }
  
  // 获取日志篮统计信息
  function getLogBasketStats() {
    const totalLogs = logItems.value.length
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    
    const todayNew = logItems.value.filter(item => {
      const itemDate = new Date(item.addedAt)
      itemDate.setHours(0, 0, 0, 0)
      return itemDate.getTime() === today.getTime()
    }).length
    
    return {
      totalLogs,
      todayNew
    }
  }
  
  // 生成唯一ID
  function generateId(): string {
    return Date.now().toString(36) + Math.random().toString(36).substr(2)
  }
  
  // 初始化
  initializeFromStorage()
  
  return {
    logItems,
    addLogItem,
    removeLogItem,
    clearLogBasket,
    cleanDuplicateLogs,
    getLogItemsByWorkspace,
    getAllLogItems,
    getLogBasketStats,
    isLogDuplicate
  }
}) 